<?php

namespace App\Admin\Controllers;

use App\Models\ArticleModel;
use App\Models\BookPermission;
use App\Models\CollectionArticle;
use App\Models\CompanyModel;
use App\Models\Support;
use App\Models\WorkModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use App\Models\BookModel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\MessageBag;

class ArticleController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '文章管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ArticleModel());

        // 最原始的`按钮图标`形式
        $grid->setActionClass(Actions::class);

        $grid->filter(function($filter) {
            // 关联查询
            $filter->where(function ($query){
                $query -> whereHas('book',function ($query){
                    $query -> where('book_title','like',"%".$this -> input."%");
                });
            },'书本名称');
        });

        $grid->column('id', __('Id'));
        $grid->column('article_title','文章标题');

        $bookModel = new BookModel();
        $grid->column('book_id', '所属书本')->display(function ($book_id)use ($bookModel){
            return $bookModel->where('id',$book_id)->value('book_title');
        });
        $grid->column('book.book_logo', '书本封面')->image('', 80, 80);
        //$grid->column('article_cover', '背景图')->image('', 180, 180);
        $grid->column('created_at', '创建时间');
        $grid->column('updated_at', '更新时间');

        // 默认为每页20条
        $grid->paginate(10);
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(ArticleModel::findOrFail($id));

        $show->field('id','文章ID');
        $show->field('article_title','文章标题');
        $show->field('article_content','文章内容');

        $show->book('所属书本', function ($book) {
            $book->setResource('/admin/book-models');
            $book->id('书本ID');
            $book->book_title('书籍名称');
            $book->book_logo('书籍封面')->image();
            $book->author('作者');
            $book->article_number('章节数');
            $book->created_at('创建时间');
        });

        $show->class_work_info('对应作业',function ($class_work_info){
            $class_work_info->setResource('/admin/work-models');

            $class_work_info->disableCreateButton();
            $class_work_info->disablePagination();
            $class_work_info->disableFilter();
            $class_work_info->disableExport();
            $class_work_info->disableRowSelector();
            $class_work_info->disableColumnSelector();
            $class_work_info->disableActions();

            $class_work_info->id('作业ID')->style('width:200px;text-align:center');
            $class_work_info->title('标题')->width(200);
            $class_work_info->describe('任务描述')->width(200);
            $class_work_info->type('提交作业类型')->using([1 => '文字', 2 => '音频'])->width(200);
        });

        $show->field('book_id','所属书本');
        $show->field('article_cover', '封面图')->image();
        $show->field('created_at', '创建时间');
        $show->field('updated_at', '更新时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ArticleModel());

        $form->text('article_title','文章标题')->attribute(['data-title' => 'title...']);

        /*     $form->select('company_id','公司')
                 ->options(
                     '/admin/company_list'
                 );*/

        $form->editor('article_content','文章内容');
        $form->text('reader_link','领读者');
        $form->file('article_leader','上传录音')
            ->move('/upload/music/'.date('Y-m-d'))
            ->uniqueName();

        //dd($_GET);
        $get = $_GET;
        $admin = Auth::guard('admin')->user()->toArray();
        if(empty($get['book_id'])){
            $form->select('book_id','书本')->options(function ($id)use($admin){
                return BookModel::where('company_id',$admin['company_id'])->pluck('book_title','id');
            })->default(0);
        }elseif(!empty($get['book_id']) && $get['book_id']!=0){
            $form->hidden('book_id')->value($get['book_id']);
        }

        $form->image('article_cover', '背景图')
            ->move('/upload/images/'.date('Ymd'))
            ->uniqueName();

        $form->hidden('playtime','时长');
        //保存前回调
        $form->saving(function (Form $form) {
            //dd($_FILES);
            //獲取时长 前端获取不到
            //dd($_FILES);
            if($_FILES['article_leader']['size']>0){
                if(!empty($_FILES['article_leader'])){
                    $path = $_FILES['article_leader']['tmp_name'];
                    $mediaTool = new \getID3();
                    $mediaInfo = $mediaTool->analyze($path);
                    //dd($mediaInfo);
                    if(empty($mediaInfo['playtime_seconds'])){
                        $error = new MessageBag([
                            'title'   => '格式错误',
                            'message' => '目前支持MP3,AAC,M4A,AMR等格式',
                        ]);

                        return back()->with(compact('error'));
                    }
                    $form->playtime = $mediaInfo['playtime_seconds'];

                }
            }
        });

        $form->deleting(function (Form $form){
            //dd(request()->route()->parameters());
            $article_id = request()->route()->parameters()['article_model'];
            CollectionArticle::where('article_id',$article_id)->delete();
            Support::where('article_id',$article_id)->delete();
        });

        $form->saved(function (Form $form) use($get) {
            // 跳转页面
            return redirect('/admin/book-models/' .$form->model()->book_id);
        });
        return $form;
    }
}
